﻿Imports System.Diagnostics
Imports System.Net
Imports System.Xml
Imports System.ServiceModel.Syndication
Imports System.Drawing
Imports System.IO
Imports TwitterModel
Imports Helper


Partial Class listtweets
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim mac As String = Request.QueryString.Item("m")
        Dim ex As String = Request.QueryString.Item("ex")
        Dim id As String = Request.Item("id")
        Dim ctx As New TwitterEntities

        If String.IsNullOrEmpty(mac) Then mac = "0000000000"
        If String.IsNullOrEmpty(ex) Then ex = "snom"

        Update(ctx, mac, ex, GetTweetsFromTwitter(ex))


        Dim tweets = ctx.Searches.Where(Function(s) (s.Mac = mac And s.Expression = ex)).First.Tweets.OrderByDescending(Function(t) (t.Id)).ToList()

        Dim mnuTitle As String = String.Format("{0} tweet{1} found for : ""{2}""", tweets.Count, IIf(tweets.Count > 1, "s", ""), ex)

        Dim sb As New StringBuilder

        Dim xml = <?xml version="1.0" encoding="UTF-8"?>
                  <SnomIPPhoneMenu>
                      <Title><%= mnuTitle %></Title>
                      <%= From tweet As Tweet In tweets
                          Select GetMenuItem(tweet, mac, ex, id)
                      %>
                      <SoftKeyItem>
                          <Name>CANCEL</Name>
                          <Label>Back to Search</Label>
                          <URL><%= Helper.TweetSearchUrl(Page, ex) %></URL>
                      </SoftKeyItem>
                  </SnomIPPhoneMenu>

        Response.ContentType = "text/xml"
        Response.Write(xml)
        Response.End()

    End Sub

    Private Function GetMenuItem(ByVal tweet As Tweet, ByVal mac As String, ByVal ex As String, ByVal id As String) As XElement
        Dim model As String = Helper.GetSnomModel(Request.UserAgent)

        Dim len As Integer = 80
        Select Case model
            Case 370
                len = 40
            Case 820, 821
                len = 25
            Case 870
                len = 20
        End Select

        Dim x As XElement = <Menuitem>
                                <%= <Name><%= Left(String.Format("{0} : {1}", tweet.UserAlias, tweet.Msg), len) %>...</Name> %>
                                <Url><%= TweetDetailUrl(Page, mac, ex, tweet.Id) %></Url>
                            </Menuitem>
        If tweet.Id = id Then x.Add(New XAttribute("sel", "true"))
        Return x
    End Function

End Class
